Skip to content

一、基础知识

1.1 静态资源存放

  1. SpringBoot 从 classpath/static 的目录 resources/static
  2. ServletContext 根目录下 src/main/webapp

1.2 异常处理

  1. 自定义错误页面

SpringBoot 默认的处理异常的机制:SpringBoot 默认的已经提供了一套处理异常的机制。 一旦程序中出现了异常 SpringBoot 会像/error 的 url 发送请求。在 springBoot 中提供了一个 叫 BasicExceptionController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常 信息

如果我们需要将所有的异常统一跳转到自定义的错误页面,需要 在src/main/resources/templates 目录下创建 error.html 页面。注意:名称必须叫 error 2. @ExceptionHandle 注解处理异常

java
//在controller中的方法上添加,可以处理这个controller发生的异常

/**
* 处理java.lang.ArithmeticException 类型的异常
* 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定 
* 参数 Exception e:会将产生异常对象注入到方法中
*/
@ExceptionHandler(value={java.lang.ArithmeticException.class}) 
public ModelAndView arithmeticExceptionHandler(Exception e){ 
    ModelAndView mv = new ModelAndView(); 
    mv.addObject("error", e.toString());
    mv.setViewName("error1"); 
    return mv; 
}
  1. @ControllerAdvice+@ExceptionHandler 注解处理异常
java
/* 全局异常处理类 
*
**/ 
@ControllerAdvice 
public class GlobalException {
    /**
    * 处理java.lang.ArithmeticException 类型异常
    * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视 图的指定 
    * 参数 Exception e:会将产生异常对象注入到方法中 
    *
    / @ExceptionHandler(value={java.lang.ArithmeticException.class}) 
    public ModelAndView arithmeticExceptionHandler(Exception e){
    ModelAndView mv = new ModelAndView(); 
    mv.addObject("error", e.toString());
    mv.setViewName("error1");
    return mv; 
    }
}
  1. 配置 SimpleMappingExceptionResolver 处理异常
java
/**
在全局异常类中添加一个方法完成异常的统一处理
* 通过 SimpleMappingExceptionResolver 做全局异常处理 
*
**/
@Configuration 
public class GlobalException {
    /**
    * 该方法必须要有返回值。返回值类型必须是: SimpleMappingExceptionResolver 
    */ 
    @Bean 
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ 
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties(); 
        /**
        * 参数一:异常的类型,注意必须是异常类型的全名 
        * 参数二:视图名称 
        */ 
      mappings.put("java.lang.ArithmeticException", "error1");
  mappings.put("java.lang.NullPointerException","error2"); 
        //设置异常与视图映射信息的
        resolver.setExceptionMappings(mappings); return resolver; 
    } 
}
  1. 自定义 HandlerExceptionResolver 类处理异常
java
/**
* 通过实现 HandlerExceptionResolver 接口做全局异常处理 
*
**/ 
@Configuration 
public class GlobalException implements HandlerExceptionResolver { 
    @Override 
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 
        ModelAndView mv = new ModelAndView(); 
        //判断不同异常类型,做不同视图跳转 
        if(ex instanceof ArithmeticException){ 
            mv.setViewName("error1"); 
        }
        if(ex instanceof NullPointerException){
            mv.setViewName("error2");
        }
        mv.addObject("error", ex.toString());
        return mv;
    }
}

1.3 核心注解

  • @SpringBootApplication:代表是 SpringBoot 的启动类。
  • @SpringBootConfiguration:通过 bean 对象来获取配置信息
  • @Configuration:通过对 bean 对象的操作替代 spring 中 xml 文件
  • @EnableAutoConfiguration:完成一些初始化环境的配置。
  • @ComponentScan:来完成 spring 的组件扫描。替代之前我们在 xml 文件中配置组件扫描的 配置<context:component-scan pacage=”....”>
  • @RestController:1,表示一个 Controller。2,表示当前这个 Controller 下的所有的方法都会以 json 格式的数据响应。

二、配置文件

2.1 多环境配置

语法结构:application-{profile}.properties profile:代表的就是一个环境变量 运行环境时命令 java -jar xxx.jar --spring.profiles.active={profile} 如:java -jar springboot-helloworld-0.0.1-SNAPSHOT.jar --spring.profiles.active=test|dev|prod

2.2 配置文件类型和作用

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。 SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件 其中,application.properties文件是键值对类型的文件,之前一直在使用,所以此处不在对properties文件的格式进行阐述。除了properties文件外,SpringBoot还可以使用yml文件进行配置

2.3 配置信息项查询

SpringBoot的配置文件,主要的目的就是对配置信息进行修改的,配置时的key可以查阅SpringBoot的官方文档 文档URL:https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties 常见配置如下:

properties
# QUARTZ SCHEDULER (QuartzProperties)


<NolebasePageProperties />




spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.

# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.

# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.

# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.

# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.

# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.

可以通过配置application.poperties 或者 application.yml 来修改SpringBoot的默认配置

2.4 配置文件与配置类的属性映射方式

使用注解@Value映射

可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上 如配置:

yaml
person:
  name: zhangsan
  age: 18

实体类映射

java
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;

使用注解@ConfigurationProperties映射

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射 注意: 使用@ConfigurationProperties方式可以进行配置文件与实体字段的自动映射,但需要字段必须提供set方法才可以,而使用@Value注解修饰的字段不需要提供set方法 如配置:

yaml
person:
  name: zhangsan
  age: 18

实体类代码:

java
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;
}

三、拓展知识

3.1 监控springboot状态

Spring Boot Admin

是一个开源社区项目,用于管理和监控SpringBoot应用程序。这个项目中包含有客户端和服务端两部分,而监控平台指的就是服务端。它也是一个springboot项目

服务端

添加admin坐标

xml
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId> 
    <version>1.5.7</version>
</dependency>

启动类

java
@SpringBootApplication
@EnableAdminServer 
public class SpringbootServerApplication {
    public static void main(String[] args) {
     SpringApplication.run(SpringbootServerApplication.class, args); 
    } 
}
客户端

依赖

xml
<dependency> 
    <groupId>de.codecentric</groupId> 
    <artifactId>spring-boot-admin-starter-client</artifactId> 
    <version>1.5.7</version> 
</dependency>

配置

yaml
spring:
  boot:
    admin:
      client:
        url: http://localhost:8080
management: # 允许服务器以HTTP请求的方式获取对应的信息,否则会看不到什么有效信息
  endpoint: # 放开所有健康信息
    health:
      show-details: always
  endpoints: # 放开所有信息
    web:
      exposure:
        include: "*"

springbootadmin的客户端默认开放了13组信息给服务器,但是这些信息查看健康信息外,其他的信息都不让通过HTTP请求查看。 类加载面板中可以查阅到开发者自定义的类 映射中可以查阅到当前应用配置的所有请求 性能指标中可以查阅当前应用独有的请求路径统计数据

监控原理

监控中显示的信息实际上是通过发送请求后得到json数据。客户端通过导入了springboot admin的对应的client,其中包含了actuator的包,提供了获取相关数据的请求接口。

Actuator,可以称为端点,描述了一组监控信息,SpringBootAdmin提供了多个内置端点,通过访问端点就可以获取对应的监控信息,也可以根据需要自定义端点信息。通过发送请求路劲**/actuator可以访问应用所有端点信息,如果端点中还有明细信息可以发送请求/actuator/端点名称**来获取详细信息。

ID描述默认启用
auditevents暴露当前应用程序的审计事件信息。
beans显示应用程序中所有 Spring bean 的完整列表。
caches暴露可用的缓存。
conditions显示在配置和自动配置类上评估的条件以及它们匹配或不匹配的原因。
configprops显示所有 @ConfigurationProperties 的校对清单。
env暴露 Spring ConfigurableEnvironment 中的属性。
flyway显示已应用的 Flyway 数据库迁移。
health显示应用程序健康信息
httptrace显示 HTTP 追踪信息(默认情况下,最后 100 个 HTTP 请求/响应交换)。
info显示应用程序信息。
integrationgraph显示 Spring Integration 图。
loggers显示和修改应用程序中日志记录器的配置。
liquibase显示已应用的 Liquibase 数据库迁移。
metrics显示当前应用程序的指标度量信息。
mappings显示所有 @RequestMapping 路径的整理清单。
scheduledtasks显示应用程序中的调度任务。
sessions允许从 Spring Session 支持的会话存储中检索和删除用户会话。当使用 Spring Session 的响应式 Web 应用程序支持时不可用。
shutdown正常关闭应用程序。
threaddump执行线程 dump。
heapdump返回一个 hprof 堆 dump 文件。
jolokia通过 HTTP 暴露 JMX bean(当 Jolokia 在 classpath 上时,不适用于 WebFlux)。
logfile返回日志文件的内容(如果已设置 logging.file 或 logging.path 属性)。支持使用 HTTP Range 头来检索部分日志文件的内容。
prometheus以可以由 Prometheus 服务器抓取的格式暴露指标。

端点每一项代表被监控的指标,如果对外开放则监控平台可以查询到对应的端点信息,如果未开放则无法查询对应的端点信息。通过配置可以设置端点是否对外开放功能。使用enable属性控制端点是否对外开放。其中health端点为默认端点,不能关闭。

yaml
management:
  endpoint:
    health:						# 端点名称
      show-details: always
    info:						# 端点名称
      enabled: true				# 是否开放

springboot admin设置了13个较为常用的端点作为默认开放的端点,可通过配置同一开启

yaml
management:
  endpoints:
    enabled-by-default: true	# 是否开启默认端点,默认值true

端点开启后,可以通过端点对应的路径查看对应的信息。但是此时还不能通过HTTP请求查询此信息,还需要开启通过HTTP请求查询的端点名称,使用“*”可以简化配置成开放所有端点的WEB端HTTP请求权限。

yaml
management:
  endpoints:
    web:
      exposure:
        include: "*"

对于端点的配置有两组信息,一组是endpoints开头的,对所有端点进行配置,一组是endpoint开头的,对具体端点进行配置。

yaml
management:
  endpoint:		# 具体端点的配置
    health:
      show-details: always
    info:
      enabled: true
  endpoints:	# 全部端点的配置
    web:
      exposure:
        include: "*"
    enabled-by-default: true
自定义监控指标

端点描述了被监控的信息,除了系统默认的指标,还可以自行添加显示的指标。有一下三种方式。 INFO端点 info端点描述了当前应用的基本信息,可以通过两种形式快速配置info端点的信息 配置方式

yaml
info:
  appName: @project.artifactId@
  version: @project.version@
  company: 传智教育
  author: itheima

代码修改

java
@Component
public class InfoConfig implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("runTime",System.currentTimeMillis());		//添加单个信息
        Map infoMap = new HashMap();		
        infoMap.put("buildTime","2006");
        builder.withDetails(infoMap);									//添加一组信息
    }
}

Health端点 health端点描述当前应用的运行健康指标,即应用的运行是否成功。通过编程的形式可以扩展指标信息。

java
@Component
public class HealthConfig extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        boolean condition = true;
        if(condition) {
            builder.status(Status.UP);					//设置运行状态为启动状态
            builder.withDetail("runTime", System.currentTimeMillis());
            Map infoMap = new HashMap();
            infoMap.put("buildTime", "2006");
            builder.withDetails(infoMap);
        }else{
            builder.status(Status.OUT_OF_SERVICE);		//设置运行状态为不在服务状态
            builder.withDetail("上线了吗?","你做梦");
        }
    }
}

Metrics端点 metrics端点描述了性能指标,除了系统自带的监控性能指标,还可以自定义性能指标。

java
@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {
    @Autowired
    private BookDao bookDao;

    private Counter counter;

    public BookServiceImpl(MeterRegistry meterRegistry){
        counter = meterRegistry.counter("用户付费操作次数:");
    }

    @Override
    public boolean delete(Integer id) {
        //每次执行删除业务等同于执行了付费业务
        counter.increment();
        return bookDao.deleteById(id) > 0;
    }
}

自定义端点 由于此端点数据spirng boot admin没有展示页面,因此,需要通过HTTP请求路径可以获取到当前端点的信息,但是需要先开启当前端点对外功能,或者设置当前端点为默认开发的端点。

java
@Component
@Endpoint(id="pay",enableByDefault = true)
public class PayEndpoint {
    @ReadOperation
    public Object getPay(){
        Map payMap = new HashMap();
        payMap.put("level 1","300");
        payMap.put("level 2","291");
        payMap.put("level 3","666");
        return payMap;
    }
}

Actuator自带监控

依赖

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter- actuator</artifactId> 
</dependency> 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId> 
</dependency>

直接访问: http://localhost:8080/actuatorhttp://localhost:8080/actuator/info 为查看配置中以info开头的信息。

properties
management.endpoint.health.show-details=always
# 开启后 访问 http://localhost:8080/actuator/health 可现实状态的详细信息

management.endpoints.web.exposure.include=*
# 配置后访问 http://localhost:8080/actuator 可显示所有信息